package com.tind.tindpracticeapplication.module.scan;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.huawei.hms.hmsscankit.OnResultCallback;
import com.huawei.hms.hmsscankit.RemoteView;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.tind.tindpracticeapplication.R;
import com.tind.tindpracticeapplication.module.scan.draw.ScanResultView;
import com.tind.tindpracticeapplication.module.scan.draw.ViewFinder;
import com.tind.tindpracticeapplication.module.scan.inter.IViewFinder;
import com.tind.wyf.baselib.base.BaseActivity;
import com.tind.wyf.baselib.utils.TDevice;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

import static com.huawei.hms.hmsscankit.RemoteView.REQUEST_CODE_PHOTO;
import static com.tind.tindpracticeapplication.module.scan.HuaWeiMultiScanplusActivity.SCAN_RESULT;

public class HuaWeiCustomizedScanplusActivity extends BaseActivity implements View.OnClickListener, OnResultCallback {
    public static final String SCAN_RESULT = "scanResult";
    private FrameLayout frameLayout;
    private RemoteView remoteView;
    private TextView tv_scan_mes;
    private Button mButtonChangeScan;
    private ScanResultView mScanResultView;
    private Bundle savedInstanceState;
    private ViewFinder viewFinder;
    private RemoteView.Builder mRemoteViewBuilder;
    private int mScreenWidth;
    private int mScreenHeight;
    final int SCAN_FRAME_SIZE = 240;
    final int SCAN_FRAME_SIZE_WIDTH = 75;
    final int SCAN_FRAME_SIZE_HEIGHT = 400;
    private boolean isScanFrameSize;
    private IViewFinder mIviewFinder;
    private Rect framingRect;
    private Rect oldFramingRect;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;

    }

    @Override
    protected boolean initBundle(Bundle extras) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        return super.initBundle(extras);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_hua_wei_customized_scanplus;
    }

    @Override
    protected void initView() {
        frameLayout = $(R.id.rim);
        tv_scan_mes = $(R.id.tv_scan_mes);
        mButtonChangeScan = $(R.id.button_change_scan);
        mScanResultView = $(R.id.scanResultView);
        mButtonChangeScan.setOnClickListener(this);
        mScreenWidth = getResources().getDisplayMetrics().widthPixels;
        mScreenHeight = getResources().getDisplayMetrics().heightPixels;
        isScanFrameSize = true;
    }

    @Override
    protected void initData() {
        mRemoteViewBuilder = new RemoteView.Builder()
                .setContext(this)
                .setFormat(HmsScan.ALL_SCAN_TYPE);
        mIviewFinder = new ViewFinder(this);
        viewFinder = (ViewFinder) mIviewFinder;
        framingRect = updateFramingRect();
        Log.e(TAG, "initData: " + framingRect);
        viewFinder.setFramingRect(framingRect);
        chageStatu();
    }

    private void chageStatu() {
        int childCount = frameLayout.getChildCount();
        if (childCount > 0) {
            frameLayout.removeAllViews();
            remoteView = null;
        }
        Rect rect = new Rect();
        Log.i(TAG, "chageStatu-framingRect: " + framingRect);
        Log.i(TAG, "mScreenWidth: " + mScreenWidth);
        Log.i(TAG, "mScreenHeight: " + mScreenHeight);
        //加上tabbar高度
        int topNext = (int) TDevice.dp2px(this, 70);
        rect.top = framingRect.top + topNext;
        rect.bottom = framingRect.bottom + topNext;
        rect.left = framingRect.left;
        rect.right = framingRect.right;
        Log.i(TAG, "rect-tabbar-framingRect: " + rect);
        remoteView = mRemoteViewBuilder
                .setBoundingBox(framingRect)
                .build();
        remoteView.setOnResultCallback(this);
        remoteView.onCreate(savedInstanceState);
//        FrameLayout.LayoutParams params = adjustSurface(remoteView);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        frameLayout.addView(remoteView, params);
        frameLayout.addView(viewFinder);
    }

    private FrameLayout.LayoutParams adjustSurface(RemoteView remoteView) {
        FrameLayout.LayoutParams paramSurface = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        if (getSystemService(Context.WINDOW_SERVICE) != null) {
            WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            Display defaultDisplay = windowManager.getDefaultDisplay();
            Point outPoint = new Point();
            defaultDisplay.getRealSize(outPoint);
            float sceenWidth = outPoint.x;
            float sceenHeight = outPoint.y;
            float rate;
            if (sceenWidth / (float) 1080 > sceenHeight / (float) 1920) {
                rate = sceenWidth / (float) 1080;
                int targetHeight = (int) (1920 * rate);
                paramSurface.width = LinearLayout.LayoutParams.MATCH_PARENT;
                paramSurface.height = targetHeight;
                int topMargin = (int) (-(targetHeight - sceenHeight) / 2);
                if (topMargin < 0) {
                    paramSurface.topMargin = topMargin;
                }
            } else {
                rate = sceenHeight / (float) 1920;
                int targetWidth = (int) (1080 * rate);
                paramSurface.width = targetWidth;
                paramSurface.height = LinearLayout.LayoutParams.MATCH_PARENT;
                int leftMargin = (int) (-(targetWidth - sceenWidth) / 2);
                if (leftMargin < 0) {
                    paramSurface.leftMargin = leftMargin;
                }
            }
        }
        return paramSurface;
    }

    @Override
    protected void onStart() {
        super.onStart();
        remoteView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        remoteView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        remoteView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        remoteView.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        remoteView.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_PHOTO) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
                HmsScan[] hmsScans = ScanUtil.decodeWithBitmap(HuaWeiCustomizedScanplusActivity.this, bitmap, new HmsScanAnalyzerOptions.Creator().setPhotoMode(true).create());
                if (hmsScans != null && hmsScans.length > 0 && hmsScans[0] != null && !TextUtils.isEmpty(hmsScans[0].getOriginalValue())) {
                    Intent intent = new Intent();
                    intent.putExtra(SCAN_RESULT, hmsScans[0]);
                    setResult(RESULT_OK, intent);
                    HuaWeiCustomizedScanplusActivity.this.finish();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_change_scan:
                if (isScanFrameSize) {
                    DisplayMetrics dm = getResources().getDisplayMetrics();
                    float density = dm.density;
                    Rect rect = new Rect();
                    int scanFrameSize = (int) (SCAN_FRAME_SIZE * density);
                    rect.left = mScreenWidth / 2 - scanFrameSize / 2;
                    rect.right = mScreenWidth / 2 + scanFrameSize / 2;
                    rect.top = mScreenHeight / 2 - scanFrameSize / 2;
                    rect.bottom = mScreenHeight / 2 + scanFrameSize / 2;
                    framingRect = rect;
                    viewFinder.setFramingRect(framingRect);
                    isScanFrameSize = false;
                } else {
                    framingRect = updateFramingRect();
                    viewFinder.setFramingRect(framingRect);
                    isScanFrameSize = true;
                }
                remoteView.onStop();
                remoteView.onDestroy();
                chageStatu();
                remoteView.onStart();
                break;
        }
    }

    private int leftOffset = -1;//扫码框相对于左边的偏移量，若为负值，则扫码框会水平居中
    private int topOffset = -1;//扫码框相对于顶部的偏移量，若为负值，则扫码框会竖直居中

    /**
     * 设置framingRect的值（扫码框所占的区域）
     */
    private Rect updateFramingRect() {
        float widthRatio = 0.9f;//扫码框宽度占view总宽度的比例
        float heightRatio = 0.07f;
        float heightWidthRatio = 0.5626f;//扫码框的高宽比
        Point viewSize = new Point(mScreenWidth, mScreenHeight);
        int width = viewFinder.getWidth() * 801 / 1080, height = viewFinder.getHeight() * 811 / 1080;
        width = (int) (mScreenWidth * widthRatio);
//        height = (int) (mScreenHeight * heightRatio);
        height = (int) (heightWidthRatio * width) / 4;

        int left, top;
        if (leftOffset < 0) {
            left = (viewSize.x - width) / 2;//水平居中
        } else {
            left = leftOffset;
        }
        if (topOffset < 0) {
            top = (viewSize.y - height) / 2;//竖直居中
        } else {
            top = topOffset;
        }
        return new Rect(left, top, left + width, top + height);
    }

    @Override
    public void onResult(HmsScan[] result) {
        if (result != null && result.length > 0 && result[0] != null &&
                !TextUtils.isEmpty(result[0].getOriginalValue())) {
            Rect borderRect = result[0].getBorderRect();
            String rect = "\nleft：" + borderRect.left + "\nright：" + borderRect.right + "\ntop：" + borderRect.top + "\nbottom：" + borderRect.bottom;
            String originalValue = result[0].getOriginalValue() + "\n" + rect;
            Log.e(TAG, "onResult: " + result[0].getBorderRect());
            Log.e(TAG, "getOriginalValue: " + result[0].getOriginalValue());
            HmsScan hmsScan = result[0];
            tv_scan_mes.setText(originalValue);
            mScanResultView.clear();
            mScanResultView.add(new ScanResultView.HmsScanGraphic(mScanResultView, result[0], Color.YELLOW));
            mScanResultView.setCameraInfo(mScreenWidth, mScreenHeight);
            mScanResultView.invalidate();
//            Intent intent = new Intent();
//            intent.putExtra(SCAN_RESULT, result[0]);
//            setResult(RESULT_OK, intent);
//            finish();
        }
    }
}